#!/usr/bin/bash

######################################################################
# @author      : Xiaotian Wu (yetist@gmail.com)
# @file        : toolchain.sh
# @created     : 星期三 5月 22, 2024 09:04:07 CST
#
# @description : 制作OHOS LoongArch 工具链
######################################################################
set -ex

START_DIR=`realpath $PWD`
OHOS_BUILD_TOP=${START_DIR}/openharmony_toolchains
LOCAL_BIN_DIR=$HOME/bin
export PATH=$LOCAL_BIN_DIR:$PATH

mkdir -p $OHOS_BUILD_TOP $LOCAL_BIN_DIR
# 设置Python 符号链接
if which python3 >/dev/null; then
  python_version_string=$(python3 --version | awk '{print $2}')
  python_cmd=`which python3`
elif which python >/dev/null; then
    python_version_string=$(python --version | awk '{print $2}')
    python_cmd=`which python`
fi
if [[ ! "$python_version_string" =~ ^3.* ]];then
    echo "Please install Python-3.x"
else
    ln -sf `which ${python_cmd}` $LOCAL_BIN_DIR/python
fi

# 克隆 git-repo
pushd $OHOS_BUILD_TOP

if [ ! -f $LOCAL_BIN_DIR/repo ]; then
    curl https://gitee.com/oschina/repo/raw/main/repo -o $LOCAL_BIN_DIR/repo
    chmod +x $LOCAL_BIN_DIR/repo
fi

# Ubuntu
#sudo apt-get install build-essential swig python3-dev libedit-dev libncurses5-dev binutils-dev gcc-multilib abigail-tools rsync

if [ ! -f .repo/manifests/llvm-toolchain.xml ]; then
    repo init -u https://gitee.com/openharmony-loongarch/manifest.git -b master -m llvm-toolchain.xml --no-repo-verify
    repo sync #-c
    repo forall -c 'git lfs pull'
fi

# update prebuilts, no need to run each time
if [ ! -f download_packages/clang_linux-x86_64-*.tar.gz ]; then
    ./toolchain/llvm-project/llvm-build/env_prepare.sh
fi

# create clang toolchains with loongarch64
python3 ./toolchain/llvm-project/llvm-build/build.py

# create rust toolchains with loongarch64
./devtools/rust-build.sh
